package com.hongbao.game.service;

import com.hongbao.game.model.BatchPrize;
import com.hongbao.game.model.Game;
import com.hongbao.game.model.Prize;
import com.hongbao.game.model.User;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class GameService_Lua {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    PrizeService prizeService;

    public Game findById(Long id){
        //从数据库查询
        Date now = new Date();
        Game game = new Game(1L,"Rain",now,
                new Date(now.getTime()+120*1000),1);
        return game;
    }


    public void attachPrize(Game game, List<BatchPrize> batchPrizeList) {
        List<Prize> prizeList = shufflePrizeAndGenerateTimeStamp(game, batchPrizeList);

        //在redis中建立关联
        //game 和 关联的奖品
        for (Prize prize : prizeList) {
            redisTemplate.opsForList().rightPush("game_prize_"+game.getId(),prize);

            redisTemplate.opsForList().rightPush("game_prize_timestamp_"+game.getId(),prize.getTimestampMS());
        }
    }


    @Autowired
    RedissonClient redissonClient;
    /**
     * 抽中返回Prize
     * 否则返回null
     * @param gameId
     * @param user
     * @return
     */
    public String takePartGame(Long gameId, User user) {
        Game game = findById(gameId);
        Date now1 = new Date();
        boolean now_before_startTime = now1.before(game.getStartTime());
        if (now_before_startTime) {
            return "活动尚未开始";
        }

        boolean now_after_endTime = now1.after(game.getEndTime());
        if (now_after_endTime) {
            return "活动已经结束";
        }

        Integer user_limit = (Integer) redisTemplate.opsForHash().get("game_limit_" + gameId, user.getLevel().toString());

        DefaultRedisScript<Prize> defaultRedisScript = new DefaultRedisScript<>();
        defaultRedisScript.setResultType(Prize.class);
        defaultRedisScript.setScriptSource(
                new ResourceScriptSource(new ClassPathResource("redis/game_prize_timestamp.lua")));

        List<String> keyList = new ArrayList<>();
        keyList.add("game_prize_timestamp_" + gameId);//只保存了时间戳
        keyList.add("game_prize_" + gameId);//奖品
        keyList.add("game_user_" + gameId);//用户抽的次数
        Object result =  redisTemplate.execute(defaultRedisScript,keyList,
                user_limit,//用户的限制
                user.getId().toString());//用户ID

        if(result instanceof  Long){
            System.out.println(result);
            Long code = (Long)result;
            if(code==0){
                return "次数超限";
            }else if(code==1){
                return "没有抢到";
            }else{
                return "已经抢完了";
            }
        }else {
            Prize prize = (Prize)result;
            return prize.toString();
        }
    }

    /**
     * 打散所有的批次的奖品
     * 并且生成时间戳
     * @param game
     * @param batchPrizeList
     * @return
     */
    public List<Prize> shufflePrizeAndGenerateTimeStamp(Game game,
                                      List<BatchPrize> batchPrizeList){

        List<Prize> prizeList = prizeService.shufflePrize(batchPrizeList);
        if(game.getType()==1){
            generateTimeStamp(game,prizeList);
        }
        return prizeList;
    }

    private void generateTimeStamp(Game game,
            List<Prize> prizeList){
        Date startTime = game.getStartTime();
        Date endTime = game.getEndTime();

        if(game.getType() == 1){
            Integer hongbao_count = prizeList.size();//hongbao数量
            Long hongbao_time_ms = endTime.getTime() - startTime.getTime();//时间ms

            int interval = (int)Math.ceil(hongbao_time_ms/hongbao_count);

            for(int i=0;i<hongbao_count;i++){
                Random random = new Random();
                int i1 = random.nextInt(interval);
                Prize prize = prizeList.get(i);
                prize.setTimestampMS(startTime.getTime()+i*interval + i1);
            }

            prizeList.forEach((e)->{
                System.out.println(e);
            });
        }
    }

}
